from flask import Flask, request, session, jsonify, g

app = Flask(__name__)
app.secret_key = 'bbb'

@ app.before_request
def before_request():
    """
        提前获取用户信息，简介后面的判断
        :return:
    """
    g.user = None
    if session.get('user_id') is not None:
        data = {}
        data ['user_name'] = session.get('user_name')
        data ['icon'] = session.get('icon')
        data ['user_id'] = session.get('user_id')
        g.user = data

@app.route('/login')
def login():
    user_name = request.args.get('user_name')
    password = request.args.get('password')
    if user_name == 'laowang' and password =='123456':
        session['user_name'] = 'laowang'
        session['user_id'] = 1
        session['icon'] = 'http://abcd'
        return '登录成功'
    else:
        return '登录失败'

# 必须登录的装饰器
def login_required(func):
    def wrapper(*args, **kwargs):
        # 在before_request签获取用户信息后，在这里就可以直接使用g.user
        if g.user is None:
            return jsonify(msg='请先登录')
        return func(*args, **kwargs)
    return wrapper

@app.route('/user_info')
@login_required
def user_info():
    return jsonify(g.user)

@app.route('/test')
def tset():
    if g.user is not None:
        user = g.user
    return ''
if __name__ == '__main__':
    app.run(debug=True)